<!--
 * @description  : 案件-调查处理通知书
 * @descriptionDetail: 案件-调查处理通知书
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-08-25 15:43:11
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="true" backText="返回" title="文书信息">
      <view class="theme-color" @click="printOrDown(state.canEdit)">
        {{ state.canEdit?'预览':'打印' }}
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="main-content">
      <view class="main-title">
        调查处理通知书
      </view>
      <u-form class="form-content" :model="docIns" :error-type="errorType" ref="uForm">
        <u-form-item label="文书编号" :label-position="labelPosition" :required="true">
          <u-input
            type="text"
            :clearable="false"
            :disabled="!state.canEdit"
            placeholder="请输入"
            v-model="docIns.fullDocNo"
          />
        </u-form-item>
        <u-form-item label="当事人" :label-position="labelPosition" prop="party">
          <u-input placeholder="请输入" :disabled="isDisabled" v-model="docIns.party" />
        </u-form-item>
        <u-form-item label="案发日期" :label-width="labelWidth" prop="caseDate" ref="dateChangeRef">
          <u-input placeholder="请输入" :disabled="isDisabled" v-model="docIns.caseDate" />
        </u-form-item>
        <u-form-item label="案由" :label-position="labelPosition" prop="causeOfAction" ref="caseChangeRef">
          <u-input
            type="textarea"
            height="35"
            :auto-height="true"
            placeholder="请填写案由"
            :disabled="isDisabled"
            v-model="docIns.causeOfAction"
          />
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="违反依据">
          <u-input
            type="textarea"
            placeholder="请填写其他证据"
            :disabled="isDisabled"
            v-model="docIns.punishArgument"
          />
        </u-form-item>
        <u-form-item label="协助调查期限" :label-position="labelPosition" prop="expireDays" :required="true">
          <u-input placeholder="请输入" :disabled="!state.canEdit" v-model="docIns.expireDays" />
        </u-form-item>
        <u-form-item>
          <view class="person-info">
            <view class="p-title">
              <view class="doc-sub-required">
                *
              </view>
              <view class="doc-sub-title">
                联系人
              </view>
              <view class="uicon-sty" @click="()=>{if(state.canEdit) addPerson()}">
                <u-icon name="plus-circle" color="#2979ff" size="40"></u-icon>
              </view>
            </view>
            <view class="p-content" v-for="(item,index) in personList" :key="index">
              <text class="p-width">
                {{ item.personName }}
              </text>
              <text>
                {{ item.leCertNo || item.inspectionCertNo }}
              </text>
            </view>
          </view>
        </u-form-item>
        <u-form-item label="电话" :label-position="labelPosition" prop="contactPhone" :required="true">
          <u-input placeholder="请输入" :disabled="!state.canEdit" v-model="docIns.contactPhone" />
        </u-form-item>
        <u-form-item label="地址" :label-position="labelPosition" prop="contactAddr" :required="true">
          <u-input placeholder="请输入" :disabled="!state.canEdit" v-model="docIns.contactAddr" />
        </u-form-item>
        <u-form-item
          label="文书日期"
          label-width="200"
          right-icon="arrow-right"
          :required="true"
          ref="docDateChangeRef"
        >
          <u-input
            :disabled="true"
            placeholder="请选择日期"
            class="right-text"
            v-model="docIns.docDate"
            @click="()=>{state.canEdit&&(isShowDocDate = true)}"
          />
        </u-form-item>
        <u-form-item label-width="200" label="当事人签名" label-position="left" prop="fileId">
          <view
            style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;"
            @click="showSignView"
          >
            <m-upload
              :uploadParam="{'fiGroupCode':'zmglpt-regie-zj-images'}"
              maxCount="1"
              :file-list="signImgList"
              uploadText="未签名"
              :showDefView="false"
              :deletable="state.canEdit"
              width="300rpx"
              height="150rpx"
              index="signImgList"
              :disabled="true"
              imageMode="aspectFit"
              @on-list-change="changeUpload"
            >
            </m-upload>
          </view>
          <signature :mustHor="true" :visible="isShowSignView" :disabled="!state.canEdit" @close="isShowSignView = false" @save="saveSign">
          </signature>
        </u-form-item>
      </u-form>
      <view class="bottom-btn-info" v-if="state.canEdit">
        <u-row gutter="16">
          <u-col span="6">
            <u-button plain type="primary" @click="saveOrSubmit('save')">
              保存
            </u-button>
          </u-col>
          <u-col span="6">
            <u-button type="primary" @click="saveOrSubmit('submit')">
              提交
            </u-button>
          </u-col>
        </u-row>
      </view>
    </view>
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
    <u-calendar :mode="mode" :max-date="maxDate" v-model="isShowDocDate" @change="changeDate('docDate',$event)">
    </u-calendar>
  </view>
</template>
<script>
import {
  dateUtils,
} from "@/common/util";
import PersonSelection from "@/pages/case/components/personSelection.vue";
import caseCommon from "../caseCommonMixin.js";
import officeService from "@/service/case/office.service.js";
import zjCommonService from "@/service/common/common.service";
import Signature from "@/components/signature";
import mUpload from '@/components/m-upload.vue';
import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			PersonSelection,
			Signature,
			mUpload,
			fabButton
		},
		mixins: [caseCommon, ],
		data() {
			return {
				mode: 'date',
				maxDate: '2099-12-31',
				personSelectShow: false,
				psParam: {},
				isShowRegDate: false,
				isShowDocDate: false,
				labelPosition: 'top',
				labelWidth: '360',
				errorType: ['border-bottom', 'message', ],
				regsList: [], // 先保书列表
				isDisabled: true, // 表单禁用
				rules: {
					expireDays: [{
						required: true,
						message: '请填写协助调查期限',
						trigger: ['change', 'blur', ],
					}, ],
					contactPhone: [{
							required: true,
							message: '请输入电话号码',
							trigger: ['change', 'blur', ],
						},
						{
							min: 6,
							max: 20,
							message: '长度在6-20个字符之间',
						},
					],
					docDate: [{
						required: true,
						message: '请选择文书日期',
						trigger: ['change', 'blur', ],
					}, ],
					contactAddr: [{
						required: true,
						message: '请填写地址',
						trigger: ['change', 'blur', ],
					}, ],
				},
				personList: [], // 承办人
				isAction: false,
				caseParam: {}, // 文书列表中传过来的参数
				doc: {},
				docIns: {}, // 表单数据
				saveData: {},
				isShowSignView: false,
				signImgList: [],
				btnType: "",
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}]
			}
		},
		watch: {
			isShowDocDate() {
				this.$refs.dateChangeRef.validation();
			},
			isShowRegDate() {
				this.$refs.docDateChangeRef.validation();
			},
			isAction() {
				this.$refs.caseChangeRef.validation();
			},
		},
		created() {

		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad() {
			this.caseParam = this.getRouteParam();
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo ? docInfo : {};
				this.setRightBtns();
			});
			this.initDocData();
		},
		methods: {
			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			// 初始化文书信息
			initDocData() {
				officeService.docFields(this.caseParam.docUuid, true).then(docConfigs => {
					if (docConfigs.success) {
						// 获取勘验笔录信息参数
						let parms = {
							id: this.caseParam.id,
							docUuid: this.caseParam.docUuid,
							bizUuid: this.caseParam.bizUuid,
						}
						officeService.getDocSurvey(parms).then(res => {
							let [tiInfo, rs, employeeList, ] = [{}, {},
								[],
							];
							if (res.success && res.data.length === 2) {
								tiInfo = res.data[0];
								rs = res.data[1];
								Object.keys(tiInfo).forEach(key => {
									rs[key] = tiInfo[key];
								});
								employeeList = this.parseEmployee(rs, 'contactUuids', 'contact');
							} else {
								rs = res.data[0];
								employeeList = this.parseEmployee(rs, 'contactUuids', 'contact');
							}
							this.docIns = rs;
							this.personList = employeeList;
							if (!this.$u.test.isEmpty(this.docIns.fileId)) {
								this.signImgList = [{
									gfiId: this.docIns.fileId,
								}, ];
							}
						});
					} else {
						this.$u.toast(docConfigs.msg);
					}
				});
			},
			changeDate(type, e) {
				this.docIns[type] = dateUtils.dateFormat("yyyy年MM月dd日", new Date(e.result));
				if (type == 'docDate') this.$refs.docDateChangeRef.validation();
			},
			// 打印/预览
			printOrDown(flag) {
				if (flag) {
					// 调接口预览
					this.saveOrSubmit('preview');
				} else {
					this.downloadFile(this.doc.pdfFileId);
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast("没有文书");
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			saveSign(v) {
				console.log(v);
				this.isShowSignView = false;
				this.$modal.showLoading('保存签名...');
				let uploadParam = {
					'fiGroupCode': 'zmglpt-regie-zj-images',
				};
				uploadParam.fileName = Date.now() + '.jpg';
				zjCommonService.uploadBase64ForApp(v, uploadParam).then(res => {
					this.$modal.hideLoading();
					if (res.success) {
						this.signImgList = [res.bean, ]
						this.docIns.fileId = res.bean.gfiId;
					} else {
						console.log(res.msg);
						this.$u.toast('签名信息保存失败');
					}
				}).catch(er => {
					console.log(er);
					this.$modal.hideLoading();
					this.$u.toast('签名信息保存失败');
				});
			},
			// 上传/删除图片事件
			changeUpload(list, key) {
				if (key == 'signImgList') {
					if (list.length == 0) {
						this.docIns.fileId = "";
						this.signImgList = []
					}
					return;
				}
			},
			showSignView() {
				if (!this.state.canEdit) return;
				this.isShowSignView = true;
			},
			// 表单验证
			validForm(type) {
				let basicValid = false;
				this.btnType = type;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						basicValid = true;
					} else {
						basicValid = false;
					}
				});
				return basicValid;
			},
			// 保存或提交
			saveOrSubmit(type) {
				if (type == 'preview') {
					if (!this.doc.isRecorded) {
						this.$u.toast('请先保存数据');
						return;
					}
					officeService.buildLocalPunish("/survey/doc-survey-handle", this.doc.docInsUuid).then(pdfId => {
						if (pdfId.success) {
							this.downloadFile(pdfId.bean, "预览", false);
						} else {
							this.$u.toast(pdfId.msg);
						}
					});
				} else {
					let flag = this.validForm(type);
					if (flag) {
						if (!this.docIns.docNo) {
							this.$u.toast('文书编号不能为空!');
							return;
						}
						if (!this.docIns.docYear) {
							this.$u.toast('文书年份不能为空!');
							return;
						}
						if (this.docIns.docNo.length > 20) {
							this.$u.toast('文书编号请输入20位以内的字符!');
							return;
						}
						if (this.docIns.docYear.length > 4) {
							this.$u.toast('文书年份请输入4位数之内!');
							return;
						}

						this.handleOperBtn(type);
					}
				}
			},
			handleOperBtn(flag) {
				let [docGoodsReg, self, ] = [this.docIns, this, ];
				let {
					docUuid,
					id,
					titemUuid,
					type,
					bizUuid,
					caseCode,
					caseType,
					gfaCode,
				} = this.caseParam;
				docGoodsReg.caseUuid = this.caseParam.caseUuid;
				docGoodsReg.casePro = docGoodsReg.causeOfActionUuid;
				// docGoodsReg.fullDocNo = `${docGoodsReg.orgAbbr}烟调[${docGoodsReg.docYear}]${docGoodsReg.docNo}号`;
				flag == 'save' && this.$u.loading('数据保存中...');
				officeService.saveDocSurvey(docGoodsReg, docUuid, titemUuid, id, type).then((res) => {
					this.$u.hideLoading();
					if (res.success) {
						this.$u.toast(res.msg);
						let bean = res.bean;
						docGoodsReg.surveyHandleUuid = bean.surveyHandleUuid;
						this.saveData = res.data[0];
						self.doc['isRecorded'] = res.data[0].isRecorded;
						self.doc['docInsUuid'] = res.data[0].docInsUuid;
						this.docIns = docGoodsReg;
						if (flag === 'submit') {
							if (self.signImgList.length > 0) {
								this.$u.loading('数据提交中...');
								officeService.submitDocSurvey(bean, docUuid, titemUuid).then(res => {
									this.$u.hideLoading();
									this.saveBehaviorLog(1, this.caseParam, this.doc);
									if (res.success) {
										// 返回列表
										this.$u.toast(res.msg);
										self.backPrev({
											paramKey: "offiList",
											param: {
												caseUuid: bizUuid,
												caseCode: caseCode,
												caseType: caseType,
											},
										});
									} else {
										this.$u.toast(res.msg);
									}
								})
							} else {
								this.$modal.confirm('当事人未签名，是否继续提交?', () => {
									// this.$u.loading('数据提交中...');
									this.$u.loading('数据提交中...');
									officeService.submitDocSurvey(bean, docUuid, titemUuid).then(res => {
										this.$u.hideLoading();
										this.saveBehaviorLog(1, this.caseParam, this.doc);
										if (res.success) {
											// 返回列表
											this.$u.toast(res.msg);
											self.backPrev({
												paramKey: "offiList",
												param: {
													caseUuid: bizUuid,
													caseCode: caseCode,
													caseType: caseType,
												},
											});
										} else {
											this.$u.toast(res.msg);
										}
									})
								}, )
							}
						} else {
							this.saveBehaviorLog(0, this.caseParam, this.doc);
						}
					} else {
						this.$u.toast(res.msg);
					}
				});
			},
			// 添加承办人事件
			addPerson() {
				this.psParam = {
					min: 2,
					max: 2,
					caseUuid: this.caseParam.caseUuid,
				};
				this.personSelectShow = true;
			},
			handlerChoosePerson(e) {
				this.personSelectShow = false;
				this.personList = [...e, ];
				let tIds = [];
				let tNames = [];
				this.personList.forEach(el => {
					tIds.push(el.personUuid);
					tNames.push(el.personName + "(" + el.leCertNo + ")");
				});
				this.docIns['contactUuids'] = tIds.join(",");
				this.docIns['contact'] = tNames.join(",");
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "../case_common.scss";

	.doc-no {
		display: inline-block;
		height: 35px;
		width: 60px;
		text-align: center !important;
		flex: none;
	}

	.check-desc {
		display: flex;
		align-items: center;

		.dec-input {
			width: 25%;
		}
	}
</style>
